import {getGTCode, getCheckCode} from 'api/index'
import 'common/js/gt'

export var mixin = {
  computed: {
    isLogin(){
      return !!this.$store.state.uid
    }
  }
}


export var codeMixin = {
  data () {
    return {
      captchaObj: null,
      scene: 'invite',
      codeForm: {
        phone_area: '86',
        name: '',
        code: ''
      }
    }
  },
  methods: {
    captchaSuccess () {
      //console.log('===')
      console.log('captchaSuccess')
      if (this.isGetCoding) {
        return
      }
      this.isGetCoding = true
      let result = this.captchaObj.getValidate()
      let {name, phone_area} = this.codeForm
      let params = Object.assign({
        scene: this.scene,
        area: phone_area,
        mobile: name,
      }, result)
      // let gcc = this.codeType == 'shop' ? getShopGTCode : getCheckCode
      getCheckCode(params)
        .then(data => {
          this.isGetCoding = false
          //this.startTime2()
          this.onSendCodeSuccess({
            area: phone_area,
            mobile: name,
          })
        })
        .catch(e => {
          this.isGetCoding = false
          let me = this
          this.$warn(e.info);
        })



    },
    initGeetest (data, resolve, reject) {

      window.initGeetest({
        // 以下配置参数来自服务端 SDK
        gt: data.gt,
        challenge: data.challenge,
        offline: !data.success,
        product: 'bind',
        new_captcha: true
      }, (captchaObj) => {
        this.captchaObj = captchaObj
        captchaObj.onSuccess(this.captchaSuccess)
        // captchaObj.onClose(this.captchaClose)
        resolve()
        // captchaObj.onError(function () {
        //   debugger
        // })
      })
    },
    getRegister_ini () {
      // let ggc = this.codeType == 'shop' ? getShopGTCode : getGTCode
      return new Promise((resolve, reject)=> {
        getGTCode()
          .then(({data}) => {
            this.initGeetest(data, resolve, reject)
          })
          .catch(e=>{
            reject(e)
          })
      });



    },
    validCodeForm(){
      let {name} = this.codeForm
      if(!name.trim()){
        return false
      }
      if(this.isSendCode){
        return false
      }
      this.isSendCode = true
      return true
    },
    sendCode(){
      if(!this.validCodeForm()) {
        return
      }
      if (!this.captchaObj) {
        this.getRegister_ini()
          .then(()=>{
            this.isSendCode = false
            this.sendCode()
          })
          .catch(e => {
            let me = this
            this.isSendCode = false
            this.$warn('获取验证码失败,请刷新页面重试')
          })
        return
      }
      this.isSendCode = false

      if (this.isGetCoding) {
        return
      }

      setTimeout(()=>{
        this.captchaObj.verify()
      },100)

    }
  }
}








